<%@ page import="com.example.domain.Chapter" %>
<%@ page import="java.util.List" %><%--
  Created by IntelliJ IDEA.
  User: liuqing
  Date: 2024/11/17
  Time: 23:11
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<%@ include file="header.jsp"%>

<main>
    <div class="novel-detail">
        <!-- 其他内容 -->
        <div class="breadcrumb-1">
            <a href="index.jsp">首页</a> > <a href="NovelTypeServlet?category=${novel.category}">${novel.category}小说</a> > <span>${novel.title}</span>
        </div>
        <div class="novel-1">
            <div class="novel-img">
                <img src="${novel.cover_image_url}" alt="图片获取失败！" id="novel-cover" class="novel-cover">
            </div>
            <div class="novel-info">
                <h1>${novel.title}</h1>
                <span>作者：${novel.author}</span>
                <span>更新时间：${novel.update_time}</span>
                <a href="#" class="btn" id="bnt-botton">直达底部</a>
                <div class="novel-status">
                    <p>状态：${novel.statu_s}</p>
                    <p>最新章节：${lastTitle}</p><br>
                    <a href="BookShelfAddServlet" class="btn">加入书架</a>
<%--                    <a href="NovelContentServlet?chapter_id=${read_chapter_id}" class="btn">点击阅读</a>--%>
                    <a href="NovelContentServlet?chapter_id=${chapterList.get(0).chapter_id}" class="btn">点击阅读</a>
                </div>
            </div>
        </div>
        <div class="novel-intro">
            <p>简介：</p>
            <p>${novel.description}</p>
        </div>
        <div class="chapter-list">
            <h3>章节列表，共 ${fn:length(chapterList)} 章</h3>
            <ul class="chapter-list-1">
<%--                <c:forEach var="chapter" items="${chapterList}">--%>
<%--                    <a href="NovelContentServlet?chapter_id=${chapter.chapter_id}"><li>${chapter.title}</li> </a><!-- 假设章节对象有一个名为title的属性 -->--%>
<%--                </c:forEach>--%>
                    <c:forEach var="chapter" items="${chapterList}" varStatus="status">
                        <c:choose>
                            <c:when test="${status.last}">
                                <!-- 最后一章 -->
                                 <li class="locked-chapter" data-chapter-id="${chapter.chapter_id}" onclick="showPaymentModal('${fn:escapeXml(chapter.title)}', '${chapter.chapter_id}','${novel.title}','${user.user_id}','${novel.novel_id}')">
                                    ${chapter.title}<i class="fa-solid fa-lock" style="color: #bababa;margin-left: 10px;"></i>
                                 </li>
                            </c:when>
                            <c:otherwise>
                                <!-- 其他章节 -->
                                <a href="NovelContentServlet?chapter_id=${chapter.chapter_id}"><li>${chapter.title}</li></a>
                            </c:otherwise>
                        </c:choose>
                    </c:forEach>
            </ul>
            <!-- 支付对话框 -->
            <div id="paymentModal" class="modal">
                <div class="modal-content">
                    <span class="close" onclick="closeModal()">&times;</span>
                    <h2 style="margin-top: 10px">购买章节</h2>
                    <div id="chapterInfo"></div>
                    <button class="pay-button" onclick="processPayment()">立即支付</button>
                </div>
            </div>
        </div>
    </div>
</main>

<script>
    var btn = document.getElementById('bnt-botton');
    document.getElementById('novel-cover').onerror = function() {
        this.onerror = null; // 防止无限循环
        this.src = 'novelimg/none.jpg'; // 替换为本地图片路径
    };
    document.getElementById('bnt-botton').onclick = function() {
        // 阻止链接的默认行为
        event.preventDefault();
        window.scrollTo({
            top: document.body.scrollHeight,
            behavior: 'smooth'
        });
       btn.style.color = 'white';
    };
</script>
<script>
    function showPaymentModal(title, chapterId,name,user_id,novel_id) {
        const modal = document.getElementById('paymentModal');
        const chapterInfo = document.getElementById('chapterInfo');

        // 存储所有需要的数据
        modal.dataset.chapterId = chapterId;
        modal.dataset.chapterTitle = title;
        modal.dataset.novelName = name;
        modal.dataset.user_id = user_id;
        modal.dataset.novel_id = novel_id;

        //console.log('Debug:', {title, chapterId}); // 添加调试输出
        chapterInfo.innerHTML = chapterInfo.innerHTML = '<p>小说：'+name+'</p>'+'<p>章节：' + title + '</p>' +
            '<p>价格：￥1</p>' +
            '<p>购买后即可阅读</p>';

        modal.style.display = 'block';
    }

    function closeModal() {
        const modal = document.getElementById('paymentModal');
        modal.style.display = 'none';
    }

    function processPayment() {
        const modal = document.getElementById('paymentModal');
        // 获取存储的所有数据
        const chapterId = modal.dataset.chapterId;
        const chapterTitle = modal.dataset.chapterTitle;
        const novelName = modal.dataset.novelName;
        const user_id = modal.dataset.user_id;
        const novel_id = modal.dataset.novel_id;
        // 这里添加实际的支付处理逻辑
        // 假设使用AJAX发送支付请求
        fetch('AlipayServlet', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                chapter_id: chapterId,
                chapter_title: chapterTitle,
                novel_name: novelName,
                price: '1.00',  // 章节价格
                user_id: user_id,
                novel_id: novel_id,
                subject: novelName +'-'+ chapterTitle, // 订单标题
                body: '购买小说《'+novelName+'》的章节：'+chapterTitle // 订单描述
            })
        }).then(response => response.text())
            .then(htmlForm => {
                const div = document.createElement('div');
                div.innerHTML = htmlForm;
                document.body.appendChild(div);

                const form = div.querySelector('form');
                if (form) {
                    form.submit();
                } else {
                    throw new Error('支付表单生成失败');
                }
            })
            .catch(error => {
                console.error('支付错误:', error);
                alert('生成支付订单失败，请重试');
            });
    }

    // 点击模态框外部关闭
    window.onclick = function(event) {
        const modal = document.getElementById('paymentModal');
        if (event.target == modal) {
            modal.style.display = 'none';
        }
    }
    // 添加支付成功后的处理函数
    function handlePaymentSuccess(chapterId) {
        // 1. 找到对应的章节元素
        const lockedChapter = document.querySelector(`li[data-chapter-id="${chapterId}"]`);
        if (!lockedChapter) return;

        // 2. 移除锁图标
        const lockIcon = lockedChapter.querySelector('.fa-lock');
        if (lockIcon) {
            lockIcon.remove();
        }

        // 3. 移除点击事件，添加链接
        lockedChapter.onclick = null;
        lockedChapter.classList.remove('locked-chapter');

        // 4. 将章节转换为可点击链接
        const chapterLink = document.createElement('a');
        chapterLink.href = `NovelContentServlet?chapter_id=${chapterId}`;

        // 保存原有内容
        const chapterContent = lockedChapter.innerHTML;

        // 将章节包装在链接中
        while (lockedChapter.firstChild) {
            chapterLink.appendChild(lockedChapter.firstChild);
        }
        lockedChapter.appendChild(chapterLink);

        // 5. 关闭支付模态框
        closeModal();
    }

    // 修改支付成功回调页面的处理
    window.onPaymentSuccess = function(chapterId) {
        handlePaymentSuccess(chapterId);
        // 可以选择是否立即跳转到章节内容
        // window.location.href = `NovelContentServlet?chapter_id=${chapterId}`;
    };
</script>
<%@ include file="footer.jsp"%>
